System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

65% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Day 9: Streaming & Big Data
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design a Live Comment Streaming Service (Twitch Chat)
Image

Here is the step-by-step system design for a Live Comment Streaming Service like Twitch Chat.

1. Problem Definition and Scope

We are designing a real-time chat infrastructure where millions of users can watch a live video stream and interact via text. The system must handle massive spikes in traffic during popular events.

  • Main User Groups:

    • Viewers: Join channels, read live chat, and send messages.

    • Streamers: Broadcast content and interact with the chat.

  • Main Actions: Joining a room, sending a message, and receiving a stream of messages in real-time.

  • Scope:

    • We will focus on text chat delivery and storage.

    • We will not cover video streaming, payments, user management, or complex moderation bots.

Image

2. Clarify functional requirements

Must Have:

  • Join Chat: Users can connect to a specific channel's chat room.

  • Send Message: Users can post messages to the chat.

  • Receive Messages: Users see new messages from others in real-time (< 200ms).

  • Chat History: New users see the last ~50 messages upon joining so the chat window isn't empty.

  • Scalability: Support channels ranging from 10 viewers to 1 million concurrent viewers.

Nice to Have:

  • Rate Limiting: Prevent users from spamming.

  • Viewer Count: Show the number of currently connected users.

  • Slow Mode: Ability to throttle chat speed during high traffic.

Image

3. Clarify non-functional requirements

  • Target Users: 50 million Daily Active Users (DAU).

  • Concurrency: Peak of 5 million concurrent users platform-wide.

  • Mega-Channels: A single channel can have 1 million concurrent viewers (The "Thundering Herd" challenge).

  • Latency: End-to-end delivery under 200ms.

  • Availability: 99.99%. Dropping a few messages is acceptable; total downtime is not.

  • Consistency: Eventual consistency is fine. It is okay if two users see messages in a slightly different order during high load.

  • Write Pattern: Write-heavy (append-only).

  • Read Pattern: Massive Fan-out. 1 incoming message → 1 million outgoing deliveries.

Image

4. Back of the envelope estimates

Traffic Estimates (The Mega-Channel Scenario):

  • Viewers: 1,000,000 concurrent in one room.
  • Write Throughput (Ingest):
    • Assume 1% of viewers send a message every second (very active).
    • messages/sec (incoming).
  • Fan-out Throughput (Egress):
    • Every incoming message must be pushed to all 1 million viewers.
    • .
    • Note: 10 Billion events/sec is extremely expensive and technically difficult. We must use message shedding and batching (humans cannot read 10k messages/sec anyway).

Storage Estimates:

  • Message Size: 100 bytes (text + metadata).
  • Daily Volume: Assume 500 million messages/day platform-wide.
  • .
  • Yearly: .
  • Conclusion: Storage is trivial. Bandwidth and CPU for fan-out are the bottlenecks.
Image

5. API design

We will use WebSockets (WSS) for the live chat because HTTP polling is too slow and resource-heavy for real-time interaction.1 We will use REST for initial history loading.

1. GET /api/v1/chat/{channel_id}/history

  • Description: Fetches the last 50 messages to populate the UI.
  • Response: [{ "user": "Alice", "text": "Hi", "ts": 167000... }, ...]

2. WebSocket: Connect

  • Endpoint: wss://chat.service.com/connect?token={jwt}&channel_id={id}
  • Behavior: Authenticates the user and upgrades the connection to a persistent WebSocket.

3. WebSocket: Send Message (Client Server)

  • Payload:
{ "type": "SEND", "content": "Hello Streamer\!", "timestamp": 1678888888 }

4. WebSocket: Receive Message (Server Client)

  • Payload:
{ "type": "MSG", "id": "msg\_123", "user": "Bob", "content": "Hello Streamer\!", "color": "\#FF0000" }

6. High level architecture

We separate the Stateful layer (holding connections) from the Stateless layer (business logic) and split the data flow into a Hot Path (Live) and Cold Path (Storage).

Component Responsibilities:

  • Client: Maintains the WebSocket connection.

  • Load Balancer: Distributes millions of WebSocket connections across Gateway servers.

  • Gateway Service (Stateful): Holds open TCP connections. It does no complex logic. It maps ChannelID List<Sockets> and pushes data to clients.

  • Chat Service (Stateless): Handles "Send Message" logic. It sanitizes text, checks rate limits, and routes data to the Hot and Cold paths.

  • Pub/Sub (Redis or Custom Relay): The message bus. It routes messages from the Chat Service to the specific Gateways that have users watching that stream.

  • Kafka (Message Queue): Buffers messages for the database to ensure writes don't slow down live chat.

  • Database (Cassandra): Persists chat history.

Image

7. Data model

We need a database that handles heavy write throughput and efficient time-range reads.

Choice: Cassandra (or ScyllaDB).

  • Why? It scales writes linearly and is excellent for time-series data. SQL would struggle with locking on the "Mega-Channel" write load.

Table: messages

  • channel_id (Partition Key): Groups messages by stream.

  • bucket (Partition Key): E.g., 2023-10-27-Hour-1. Optimization: Prevents partitions from becoming too large during long streams.

  • timestamp (Clustering Key): Sorts messages by time.

  • message_id (Clustering Key): Unique ID to handle collisions.

  • user_id: Who sent it.

  • content: The text.

Query:

SELECT * FROM messages WHERE channel_id = 'abc' AND bucket = '...' ORDER BY timestamp DESC LIMIT 50

8. Core flows end to end

This section is the heart of the system. It describes the lifecycle of a message from the moment a user presses "Enter" to the moment it appears on millions of screens (and is safely stored in the database).

To understand this effectively, we must recognize that this system is solving two opposing problems simultaneously:

  1. Low Latency (The Hot Path): Delivering data instantly to active viewers.

  2. High Reliability (The Cold Path): Ensuring data is never lost, even if it takes a few seconds to save.

Here is a detailed breakdown of the three core flows.

Flow 1: Sending and Receiving (The Hot Path)

Goal: Deliver a message from User A to User B, C, D... (up to 1 million users) in under 200ms.

This flow prioritizes speed over everything else. We do not wait for the database to confirm the "save" before we show the message to other users.

Step 1: Ingest (The Upstream)

  • Action: User A types "Hello" and hits send.

  • Connection: User A has a persistent WebSocket connection to a specific Gateway Server (let's call it Gateway-01).

  • Routing: Gateway-01 does not process the message logic. It simply acts as a pipe, forwarding the raw message payload to the Chat Service.

Step 2: Processing (The Brain)

The Chat Service is stateless. It receives the message and performs quick checks:

  • Validation: Is the message empty? Is it too long?

  • Sanitization: Strip out malicious HTML/JS tags to prevent XSS.

  • Rate Limiting: Has User A sent more than 5 messages in the last second? If so, reject it here.

Step 3: Fan-out (The Distribution)

This is the most critical engineering challenge in the system.

  • The Problem: If the Chat Service tries to send this message to 1,000,000 users directly, it will crash. It also cannot ask a single Redis instance to "publish" to 10,000 subscriber servers; the network bandwidth on that single Redis node will saturate.

  • The Solution (Relay Tree): We use a hierarchical "Tree Topology" for distribution.

  1. Root: The Chat Service pushes the message to a Root Broker (Redis or a custom relay).

  2. Branches: The Root Broker pushes the message to 10 Intermediate Brokers.

  3. Leaves: Each Intermediate Broker pushes the message to 100 Gateway Servers.

  4. Result: The load is spread. No single node bears the full weight of the fan-out.

Step 4: Delivery (The Downstream)

  • Local Lookup: Let's say User B is watching the stream. User B is connected to Gateway-50.

  • Gateway-50 receives the message from an Intermediate Broker.

  • It checks its local memory: "Which of my connected sockets are watching Channel 123?"

  • It finds User B's socket and pushes the text "Hello" down the wire.

Image

Flow 2: Persistence (The Cold Path)

Goal: Ensure the message is permanently stored for history and replay.

This flow happens in parallel to Flow 1. It is "asynchronous," meaning the live chat doesn't wait for this to finish.

Step 1: The Fork

When the Chat Service successfully validates the message (in Flow 1, Step 2), it does two things simultaneously:

  1. Sends to the Hot Path (Pub/Sub) for live viewers.
  2. Sends to the Cold Path (Kafka) for storage.

Step 2: Buffering (Kafka)

We use a Message Queue (Kafka) here as a shock absorber.

  • Why? During a "Thundering Herd" event (e.g., a touchdown in the Super Bowl), message volume might spike to 10,000/sec.

  • If we tried to write 10,000 rows/sec directly to the database synchronously, the database might lock up or slow down.

  • Kafka ingests these writes instantly and holds them in a log.

Step 3: The Worker (Insertion)

A separate service, the Persistence Worker, reads messages from Kafka at its own pace.

  • It batches them (e.g., reads 100 messages at a time).

  • It performs a batch insert into Cassandra.

  • Outcome: Even if the database is running slowly, the live chat (Flow 1) is completely unaffected because they are decoupled.

Image

Flow 3: Load Shedding (The "Viral" Stream)

Goal: Prevent the user's browser from crashing when chat moves too fast.

This is a counter-intuitive but necessary flow. If a channel has 1 million active users and they are all typing, the incoming rate could be 100,000 messages per second.

  • The Bottleneck: It is not the server; it is the Client. A human cannot read 100 messages per second. If the browser tries to render 100 DOM elements per second, the UI will freeze (garbage collection thrashing).

The Mechanism

  1. Detection: The Chat Service detects that Channel-XYZ has exceeded a velocity threshold (e.g., > 50 messages/sec).

  2. Protection: It enables "Shedding Mode."

  3. Selective Dropping:

    • Cold Path (Storage): receives 100% of messages. The historical log must be perfect.
    • Hot Path (Live): drops a percentage of messages (e.g., 90%) before they enter the Fan-out Tree.
  4. Result: Viewers see a lively, fast-moving chat (maybe 5-10 messages/sec), which feels "live" and exciting, but their browser remains responsive.

Image

9. Caching and read performance

  • Chat History Cache (Redis):
    • When a user joins, they need the last 50 messages. Querying Cassandra for every join (100k joins/sec) is too slow.

    • Strategy: The Chat Service maintains a Redis List for active channels.

    • Write: When a message is sent, we LPUSH to the list and LTRIM to keep size fixed at 50.

    • Read: GET /history reads this Redis List.

  • User Profile Cache: Cache user details (badges, avatar URL) to avoid looking up user attributes for every message.

10. Storage, indexing and media

  • Primary Storage: Cassandra (as defined in Data Model).

  • Media (Emotes):

    • We do not store images in the database.
    • We store text codes like :smile:.
    • The Client downloads a "Manifest" of emotes on startup from a CDN.
    • When the client renders the text :smile:, it replaces it with an <img> tag pointing to the CDN URL.
  • Archival: Data older than 1 year is moved to cold storage (S3/Glacier) via a nightly ETL job to save costs.

11. Scaling strategies

  • Gateway Layer (Horizontal Scaling):
    • Bottleneck: Number of open TCP connections (file descriptors) and RAM.
    • Solution: Auto-scale group. If connections > 50k per server, spin up new Gateways.
  • Pub/Sub Layer (Tree Topology):
    • Bottleneck: A single Redis instance cannot handle pub/sub for 1 million subscribers on one channel.
    • Solution: As mentioned in Core Flows, use a Relay Tree. The message propagates down the tree, multiplying at each hop, until it reaches the edge Gateways.
  • Smart Batching:
    • Instead of sending 100 small packets per second to a user, the Gateway buffers messages for 50ms and sends one compressed "Batch Packet" containing 5 messages. This reduces syscalls and header overhead.

12. Reliability, failure handling and backpressure

  • Backpressure:
    • If a user is on a slow mobile network, the Gateway's TCP buffer for that user will fill up.
    • Policy: The Gateway drops new messages for that user ("Drop Head"). In live chat, seeing the latest message is more important than seeing one from 10 seconds ago.
  • Gateway Failure:
    • If a Gateway crashes, 50k users disconnect.
    • Jitter: Clients must use randomized backoff (0-5s) before reconnecting to prevent DDOSing the Load Balancer (Thundering Herd).
  • Database Failure:
    • If Cassandra fails, Kafka buffers the messages. Live chat continues to work. History will catch up once the DB recovers.

13. Security, privacy and abuse

  • Authentication: Standard JWT (JSON Web Token) passed in the WebSocket handshake.

  • Encryption: All connections use WSS (TLS) so ISPs cannot snoop on messages.

  • XSS Prevention: The client must treat all message content as plain text, not HTML. We sanitize inputs on the server.

  • Shadow Banning:

    • If a user is abusive, we mark them as "shadow banned."
    • Their messages are accepted by the server (so they think they are talking), but the server drops them before the Pub/Sub stage. No one else sees them.

14. Bottlenecks and next steps

  • Bottleneck: Client-side rendering. Even if the backend delivers 1000 messages/sec, the browser DOM will lag.
    • Next Step: Implement "Virtual Scrolling" or "Recycling List Views" on the frontend to only render visible nodes.
  • Bottleneck: Global Latency. Users in Asia connecting to US servers will have lag.
    • Next Step: Move Gateways to the Edge (close to users). Use a global backbone to route messages between Edge Gateways and the central Chat Service.

Summary

  • We used WebSockets for low latency.

  • We used a Tree-based Fan-out for Mega-Channel distribution.

  • We used Message Shedding to survive traffic spikes.

  • We used Cassandra for high-speed write persistence.

Design an Ad Click Aggregator
Design a Code Deployment System
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow 1: Sending and Receiving (The Hot Path)

Flow 2: Persistence (The Cold Path)

Flow 3: Load Shedding (The "Viral" Stream)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary